﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Site.Models;

namespace Site.Controllers
{
    public class ClanController : Controller
    {
        //
        // GET: /Clan/

        private BMSiteDBEntities _db = new BMSiteDBEntities();

        [Authorize]
        public ActionResult Index()
        {
            return View(_db.CLAN.ToList());
        }

        //
        // GET: /Clan/Details/5
        [AcceptVerbs(HttpVerbs.Get)]
        [Authorize]
        public ActionResult Details(System.Guid id)
        {
            var clanToView = _db.CLAN.First(m => m.CLAN_ID == id);

            var userRoles = System.Web.Security.Roles.GetRolesForUser()[0];
            var roleObj = _db.aspnet_Roles.First(m => m.RoleName == userRoles);

            ClanDetail model = new ClanDetail
            {
                clan = clanToView,
                stats = (
                    from s in _db.STATISTIC
                    where s.STAT_CLAN_ID == clanToView.CLAN_ID
                    select s
                ).OrderBy(s => s.STAT_GAMETYPE).ToList(),
                users = (from u in _db.aspnet_Users
                         where u.USER_CLAN_ID == id
                         join s in _db.STATISTIC on u.UserId equals s.STAT_USER_ID
                         where s.STAT_GAMETYPE == 1
                         select new UserClan { user = u, stats = s }).ToList(),
                roles = (
                    from a in _db.aspnet_Roles
                    where a.Description != "1" //All roles except admin
                    orderby a.Description
                    select a).ToList(),
                userRole = int.Parse(roleObj.Description)
            };

            SelectListItem si = new SelectListItem();
            List<SelectListItem> sl = new List<SelectListItem>();
            var items = (
                        from t in _db.aspnet_Roles
                        select t);
            foreach (var item in items)
            {
                si = new SelectListItem { Value = item.RoleId.ToString(), Text = item.RoleName };
                sl.Add(si);
            }
            ViewData["MyListItems"] = sl;

            return View(model);
        }

        //
        // GET: /Clan/Create
        [Authorize]
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Clan/Create

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult Create(ClanCreateModel model)
        {
            /* Tests if user is already leader of a clan*/
            if (Session.Contents["UserClanId"] != "")
                ModelState.AddModelError("", "Vous faites déjà partie d'un clan!!");

            /* Tests about clan's name*/
            if (string.IsNullOrEmpty(model.ClanName))
                ModelState.AddModelError("", "Le nom du clan est requis!!");

            var clanNameTest = _db.CLAN.FirstOrDefault(m => m.CLAN_NAME == model.ClanName);
            if (clanNameTest != null)
                ModelState.AddModelError("", "Le nom du clan est déjà utilisé!!");
            /* *********************** */

            /* Object to add in database */
            var clanToCreate = new CLAN();
            clanToCreate.CLAN_ID = System.Guid.NewGuid(); // Génération de l'id "Guid"
            clanToCreate.CLAN_LEADER_ID = new Guid(Session.Contents["user_id"].ToString()); // Ajout de l'id du current user en leader
            clanToCreate.CLAN_CREATIONDATE = System.DateTime.Now; //Date du jour
            clanToCreate.CLAN_NAME = model.ClanName;
            clanToCreate.CLAN_DESCRIPTION = model.ClanDescription;
            clanToCreate.CLAN_FORUMLINK = model.ClanForumLink;
            clanToCreate.CLAN_MEMBER_COUNT = 1;

            /* ****** Logo ****** */
            var file_path = "";
            var file_url = "";
            HttpPostedFileBase file = Request.Files["logo_upload_file"];
            if (file != null)
            {
                file_path = Server.MapPath("~") + "/Uploads/logos/" + clanToCreate.CLAN_ID + ".jpg";
                file_url = "http://" + Request.Url.Authority + "/Uploads/logos/" + clanToCreate.CLAN_ID + ".jpg";
                file.SaveAs(file_path);
            }

            var avatar_type = Request.Form["logo_type"];
            if (avatar_type == "logo_url")
            {
                clanToCreate.CLAN_LOGOURL = model.ClanLogo;
;
            }
            else if (avatar_type == "logo_upload")
            {
                clanToCreate.CLAN_LOGOURL = file_url;
            }

            var user_id = Session.Contents["user_id"].ToString();
            var userLeader = _db.aspnet_Users.First(m => m.UserId == new Guid(user_id));
            userLeader.USER_CLAN_ID = clanToCreate.CLAN_ID;

            /* Database saving */
            if (TryUpdateModel(clanToCreate))
            {
                _db.AddObject("CLAN", clanToCreate);
                _db.SaveChanges();

                /* Add null stats */
                STATISTIC stats1 = new STATISTIC();
                stats1.STAT_CLAN_ID = clanToCreate.CLAN_ID;
                stats1.STAT_ABANDONEDGAMES = 0;
                stats1.STAT_LOSTGAMES = 0;
                stats1.STAT_WONGAMES = 0;
                stats1.STAT_GAMETYPE = 1;
                STATISTIC stats2 = new STATISTIC();
                stats2.STAT_CLAN_ID = clanToCreate.CLAN_ID;
                stats2.STAT_ABANDONEDGAMES = 0;
                stats2.STAT_LOSTGAMES = 0;
                stats2.STAT_WONGAMES = 0;
                stats2.STAT_GAMETYPE = 2;
                STATISTIC stats3 = new STATISTIC();
                stats3.STAT_CLAN_ID = clanToCreate.CLAN_ID;
                stats3.STAT_ABANDONEDGAMES = 0;
                stats3.STAT_LOSTGAMES = 0;
                stats3.STAT_WONGAMES = 0;
                stats3.STAT_GAMETYPE = 3;
                STATISTIC stats4 = new STATISTIC();
                stats4.STAT_CLAN_ID = clanToCreate.CLAN_ID;
                stats4.STAT_ABANDONEDGAMES = 0;
                stats4.STAT_LOSTGAMES = 0;
                stats4.STAT_WONGAMES = 0;
                stats4.STAT_GAMETYPE = 4;

                if (TryUpdateModel(stats1) && TryUpdateModel(stats2) && TryUpdateModel(stats3) && TryUpdateModel(stats4))
                {
                    _db.AddObject("STATISTIC", stats1);
                    _db.AddObject("STATISTIC", stats2);
                    _db.AddObject("STATISTIC", stats3);
                    _db.AddObject("STATISTIC", stats4);
                    _db.SaveChanges();
                }

                //Add clan id in session
                Session.Contents["userClanId"] = clanToCreate.CLAN_ID;

                //Change user's role
                var userId = new Guid(Session.Contents["user_id"].ToString());
                var userInRole = _db.vw_aspnet_UsersInRoles.First(m => m.UserId == userId);
                var oldRole = _db.aspnet_Roles.First(m => m.RoleId == userInRole.RoleId);

                System.Web.Security.Roles.RemoveUserFromRole(User.Identity.Name, oldRole.RoleName);
                System.Web.Security.Roles.AddUserToRole(User.Identity.Name, "ClanLeader");

                return RedirectToAction("Details", new { id = clanToCreate.CLAN_ID });
            }
            else
                return View(model);
        }
        
        //
        // GET: /Clan/Edit/5
        [Authorize]
        public ActionResult Edit(System.Guid id)
        {
            /* Tests if user the leader of this clan*/
            if ((Guid)Session.Contents["UserClanId"] != id)
                return RedirectToAction("error");

            var clanToEdit = (from m in _db.CLAN
                               where m.CLAN_ID == id  
                               select m).First();

            /* Converting asp_user model to edit model to use validator classes */
            var editModel = new ClanCreateModel();
            editModel.ClanDescription = clanToEdit.CLAN_DESCRIPTION;
            editModel.ClanForumLink = clanToEdit.CLAN_FORUMLINK;
            editModel.ClanLogo = clanToEdit.CLAN_LOGOURL;
            editModel.ClanName = clanToEdit.CLAN_NAME;
            editModel.ClanId = clanToEdit.CLAN_ID;

            return View(editModel);
        }

        //
        // POST: /Clan/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult Edit(ClanCreateModel clanToEdit)
        {
            if (string.IsNullOrEmpty(clanToEdit.ClanName))
                ViewData.ModelState.AddModelError("", "Le nom de clan est requis!!");

            if (!ModelState.IsValid)
                return View();

            try
            {
                var originalClan = (from m in _db.CLAN
                                     where m.CLAN_ID == clanToEdit.ClanId
                                     select m).First();

                originalClan.CLAN_FORUMLINK = clanToEdit.ClanForumLink;
                originalClan.CLAN_DESCRIPTION = clanToEdit.ClanDescription;
                originalClan.CLAN_LOGOURL = clanToEdit.ClanLogo;

                var file_path = "";
                var file_url = "";
                HttpPostedFileBase file = Request.Files["logo_upload_file"];
                if (file != null && file.ContentLength > 0)
                {
                    file_path = Server.MapPath("~") + "/Uploads/logos/" + clanToEdit.ClanId + ".jpg";
                    file_url = "http://" + Request.Url.Authority + "/Uploads/logos/" + clanToEdit.ClanId + ".jpg";
                    file.SaveAs(file_path);
                    originalClan.CLAN_LOGOURL = file_url;
                }
                
                
                _db.SaveChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Clan/Delete/5
        [Authorize]
        public ActionResult Delete(System.Guid id)
        {
            /* Tests if user the leader of this clan*/
            if ((Guid)Session.Contents["UserClanId"] != id)
                return RedirectToAction("error");

            try
            {
                var clanToDelete = _db.CLAN.First(m => m.CLAN_ID == id);

                // Delete 
                //_db.DeleteObject(clanToDelete);
                clanToDelete.CLAN_DELETEDATE = System.DateTime.Now;
                clanToDelete.CLAN_MEMBER_COUNT = 0;

                /*Delete clan's members */
                List<aspnet_Users> users = (from u in _db.aspnet_Users
                         where u.USER_CLAN_ID == id
                         select u).ToList();

                foreach (var user in users) {
                    user.USER_CLAN_ID = null;
                }

                _db.SaveChanges();

                /* Empty clan id in session*/
                Session.Contents["userClanId"] = "";

                //Change user's role
                var userId = new Guid(Session.Contents["user_id"].ToString());
                var userInRole = _db.vw_aspnet_UsersInRoles.First(m => m.UserId == userId);
                var oldRole = _db.aspnet_Roles.First(m => m.RoleId == userInRole.RoleId);

                System.Web.Security.Roles.RemoveUserFromRole(User.Identity.Name, oldRole.RoleName);
                System.Web.Security.Roles.AddUserToRole(User.Identity.Name, "Member");
                
                // Show Index view
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // POST: /Clan/Delete/5

        [AcceptVerbs(HttpVerbs.Get)]
        [Authorize]
        public ActionResult Delete(System.Guid id, string confirmButton)
        {
            var clanToDelete = _db.CLAN.First(m => m.CLAN_ID == id);
            return View(clanToDelete);
        }


        //
        // GET: /Clan/Join/5
        [Authorize]
        public ActionResult Join(System.Guid id)
        {
            var clanToJoin = _db.CLAN.First(m => m.CLAN_ID == id);

            return View(clanToJoin);
        }

        //
        // POST: /Clan/Join/5

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult Join(CLAN clanToJoin)
        {
            var user_id = Session.Contents["user_id"].ToString();
            var user = _db.aspnet_Users.First(m => m.UserId == new Guid(user_id));
            user.USER_CLAN_ID = clanToJoin.CLAN_ID;

            var clan = _db.CLAN.First(m => m.CLAN_ID == clanToJoin.CLAN_ID);
            clan.CLAN_MEMBER_COUNT++;

            /* Putting clan id in session*/
            Session.Contents["userClanId"] = clanToJoin.CLAN_ID;

            _db.SaveChanges();

            //Change user's role
            var userId = new Guid(Session.Contents["user_id"].ToString());
            var userInRole = _db.vw_aspnet_UsersInRoles.First(m => m.UserId == userId);
            var oldRole = _db.aspnet_Roles.First(m => m.RoleId == userInRole.RoleId);

            System.Web.Security.Roles.RemoveUserFromRole(User.Identity.Name, oldRole.RoleName);
            System.Web.Security.Roles.AddUserToRole(User.Identity.Name, "ClanMember");

            return RedirectToAction("Details", new { id = clanToJoin.CLAN_ID });
        }

        //
        // GET: /Clan/Quit/5
        [Authorize]
        public ActionResult Quit(System.Guid id)
        {
            var clanToQuit = _db.CLAN.First(m => m.CLAN_ID == id);
            
            return View(clanToQuit);
        }

        //
        // POST: /Clan/Quit/5

        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult Quit(CLAN clanToQuit)
        {
            var user_id = Session.Contents["user_id"].ToString();
            var user = _db.aspnet_Users.First(m => m.UserId == new Guid(user_id));
            user.USER_CLAN_ID = null;

            var clan = _db.CLAN.First(m => m.CLAN_ID == clanToQuit.CLAN_ID);
            clan.CLAN_MEMBER_COUNT--;

            /* Empty clan id in session*/
            Session.Contents["userClanId"] = "";

            _db.SaveChanges();

            //Change user's role
            var userId = new Guid(Session.Contents["user_id"].ToString());
            var userInRole = _db.vw_aspnet_UsersInRoles.First(m => m.UserId == userId);
            var oldRole = _db.aspnet_Roles.First(m => m.RoleId == userInRole.RoleId);

            System.Web.Security.Roles.RemoveUserFromRole(User.Identity.Name, oldRole.RoleName);
            System.Web.Security.Roles.AddUserToRole(User.Identity.Name, "Member");

            return RedirectToAction("Details", new { id = clanToQuit.CLAN_ID });
        }
    }
}
